package com.szcinda.controller;


import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.EasyExcelFactory;
import com.alibaba.excel.metadata.Sheet;
import com.szcinda.repository.HistoryGhOrder;
import com.szcinda.service.DateUtils;
import com.szcinda.service.PageResult;
import com.szcinda.service.TypeStringUtils;
import com.szcinda.service.dto.history.*;
import org.springframework.beans.BeanUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.InputStream;
import java.nio.charset.StandardCharsets;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

@RestController
@RequestMapping("hisGhOrder")
public class HisGhOrderController {

    private final HistoryGhOrderService historyGhOrderService;

    public HisGhOrderController(HistoryGhOrderService historyGhOrderService) {
        this.historyGhOrderService = historyGhOrderService;
    }


    @PostMapping("/importIn")
    @OperationLogAnnotation(operDesc = "导入综合物流历史应收信息", operModel = "历史综合物流")
    public Result<?> orderImportIn(@RequestParam("file") MultipartFile file) throws Exception {
        // 解析每行结果在listener中处理
        InputStream inputStream = file.getInputStream();
        try {
            HisGhOrderExcelListener listener = new HisGhOrderExcelListener();
            EasyExcelFactory.readBySax(inputStream, new Sheet(1, 1, HistoryGhOrderImportDto.class), listener);
            for (HistoryGhOrderImportDto importData : listener.getImportDatas()) {
                importData.setType(TypeStringUtils.historyInType);
            }
            return Result.success(historyGhOrderService.importData(listener.getImportDatas()));
        } catch (Exception e) {
            e.printStackTrace();
            return Result.fail(e.getMessage());
        } finally {
            try {
                inputStream.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    @PostMapping("/importOut")
    @OperationLogAnnotation(operDesc = "导入综合物流历史应付信息", operModel = "历史综合物流")
    public Result<?> orderImportOut(@RequestParam("file") MultipartFile file) throws Exception {
        // 解析每行结果在listener中处理
        InputStream inputStream = file.getInputStream();
        try {
            HisGhOrderExcelListener listener = new HisGhOrderExcelListener();
            EasyExcelFactory.readBySax(inputStream, new Sheet(1, 1, HistoryGhOrderImportDto.class), listener);
            for (HistoryGhOrderImportDto importData : listener.getImportDatas()) {
                importData.setType(TypeStringUtils.historyOutType);
            }
            return Result.success(historyGhOrderService.importData(listener.getImportDatas()));
        } catch (Exception e) {
            e.printStackTrace();
            return Result.fail(e.getMessage());
        } finally {
            try {
                inputStream.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    @PostMapping("/createNew")
    @OperationLogAnnotation(operDesc = "创建综合物流历史记录", operModel = "历史综合物流")
    public Result<String> createNew(@RequestBody List<HistoryGhOrderImportDto> ghOrderImportDtos) {
        historyGhOrderService.createNew(ghOrderImportDtos);
        return Result.success();
    }

    @PostMapping("query")
    public PageResult<HistoryGhOrder> query(@RequestBody HisGhOrderQueryDto queryDto) {
        return historyGhOrderService.query(queryDto);
    }
    @PostMapping("lock")
    public Result<String> lock(@RequestBody HisGhOrderQueryDto queryDto) {
        historyGhOrderService.lock(queryDto.getIds());
        return Result.success();
    }

    @PostMapping("unlock")
    public Result<String> unlock(@RequestBody HisGhOrderQueryDto queryDto) {
        historyGhOrderService.unlock(queryDto.getIds());
        return Result.success();
    }

    @GetMapping("/del/{id}")
    @OperationLogAnnotation(operDesc = "删除综合物流历史记录", operModel = "历史综合物流")
    public Result<String> delete(@PathVariable String id) {
        historyGhOrderService.delete(id);
        return Result.success();
    }

    @PostMapping("export")
    public void query(@RequestParam String type, @RequestParam String ids, HttpServletResponse response) throws Exception {
        String fileName = String.format("历史综合-%s.xlsx", LocalDateTime.now().toLocalTime().toString());
        //HttpServletResponse消息头参数设置
        response.setCharacterEncoding("UTF-8");
        response.setHeader("Content-Transfer-Encoding", "binary");
        response.setHeader("Cache-Control", "must-revalidate, post-check=0, pre-check=0");
        response.setHeader("Pragma", "public");
        response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet;charset=UTF-8");
        fileName = new String(fileName.getBytes(), StandardCharsets.ISO_8859_1);
        response.setHeader("Content-Disposition", "attachment;filename=" + fileName);
        if (TypeStringUtils.historyInType.equals(type)) {
            List<HistoryGhOrderInExportVo> exportVOList = new ArrayList<>();
            List<HistoryGhOrder> historyGhOrders =
                    historyGhOrderService.listByIds(Arrays.asList(ids.split(",")));
            for (HistoryGhOrder historyGhOrder : historyGhOrders) {
                HistoryGhOrderInExportVo inExportVo = new HistoryGhOrderInExportVo();
                BeanUtils.copyProperties(historyGhOrder, inExportVo, "pickTime", "sendTime");
                inExportVo.setPickTime(DateUtils.parseLocalDate2Str(historyGhOrder.getPickTime()));
                inExportVo.setSendTime(DateUtils.parseLocalDate2Str(historyGhOrder.getSendTime()));
                exportVOList.add(inExportVo);
            }
            EasyExcel.write(response.getOutputStream(), HistoryGhOrderInExportVo.class).sheet("历史综合").doWrite(exportVOList);
        } else {
            List<HistoryGhOrder> historyGhOrders = historyGhOrderService.listByIds(Arrays.asList(ids.split(",")));
            List<HistoryGhOrderOutExportVo> exportVOList = new ArrayList<>();
            for (HistoryGhOrder historyGhOrder : historyGhOrders) {
                HistoryGhOrderOutExportVo inExportVo = new HistoryGhOrderOutExportVo();
                BeanUtils.copyProperties(historyGhOrder, inExportVo, "pickTime", "sendTime");
                inExportVo.setPickTime(DateUtils.parseLocalDate2Str(historyGhOrder.getPickTime()));
                inExportVo.setSendTime(DateUtils.parseLocalDate2Str(historyGhOrder.getSendTime()));
                exportVOList.add(inExportVo);
            }
            EasyExcel.write(response.getOutputStream(), HistoryGhOrderOutExportVo.class).sheet("历史综合").doWrite(exportVOList);
        }
    }
}
